<?php
/**
 * 发布统计控制器
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-10-05
 * Time: 20:30
 */

namespace plugin\csauto\app\controller;

use plugin\csauto\app\common\BaseController;
use plugin\csauto\app\model\TorrentReleaseModel;
use plugin\csauto\app\model\SiteModel;
use support\Request;
use support\Response;
use DateTime;
use DateInterval;

class TorrentReleaseStatisticsController extends BaseController
{
    /**
     * @var TorrentReleaseModel
     */
    protected $model = null;

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct()
    {
        $this->model = new TorrentReleaseModel;
    }

    /**
     * 显示统计页面
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        return view('torrentreleasestatistics/index');
    }

    /**
     * 获取统计数据
     *
     * @param Request $request
     * @return Response
     */
    public function getStatistics(Request $request): Response
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $quickDate = $request->input('quick_date'); // 快速日期筛选

        // 筛选参数
        $sourceSiteId = $request->input('source_site_id'); // 源站筛选

        // 优先使用手动选择的时间范围，如果没有则使用快速日期筛选
        if (empty($startDate) && empty($endDate) && $quickDate && !empty($quickDate)) {
            [$startDate, $endDate] = $this->getQuickDateRange($quickDate);
        }

        // 默认时间范围：最近30天
        if (empty($startDate) && empty($endDate)) {
            $endDate = date('Y-m-d');
            $startDate = date('Y-m-d', strtotime('-30 days'));
        }

        // 验证时间范围
        if ($startDate && $endDate && $startDate > $endDate) {
            return $this->fail('开始日期不能大于结束日期');
        }

        // 查询统计数据
        $statistics = $this->getReleaseStatistics($startDate, $endDate, $sourceSiteId);

        return $this->json(0, '获取成功', $statistics);
    }

    /**
     * 获取快速日期范围
     *
     * @param string $quickDate
     * @return array
     */
    private function getQuickDateRange(string $quickDate): array
    {
        $now = new DateTime();

        switch ($quickDate) {
            case 'today':
                return [$now->format('Y-m-d'), $now->format('Y-m-d')];

            case 'yesterday':
                $yesterday = clone $now;
                $yesterday->sub(new DateInterval('P1D'));
                return [$yesterday->format('Y-m-d'), $yesterday->format('Y-m-d')];

            case 'this_week':
                $startOfWeek = clone $now;
                $startOfWeek->modify('monday this week');
                return [$startOfWeek->format('Y-m-d'), $now->format('Y-m-d')];

            case 'last_week':
                $lastWeekStart = clone $now;
                $lastWeekStart->modify('monday last week');
                $lastWeekEnd = clone $lastWeekStart;
                $lastWeekEnd->modify('sunday this week');
                return [$lastWeekStart->format('Y-m-d'), $lastWeekEnd->format('Y-m-d')];

            case 'this_month':
                $startOfMonth = clone $now;
                $startOfMonth->modify('first day of this month');
                return [$startOfMonth->format('Y-m-d'), $now->format('Y-m-d')];

            case 'last_month':
                $lastMonthStart = clone $now;
                $lastMonthStart->modify('first day of last month');
                $lastMonthEnd = clone $now;
                $lastMonthEnd->modify('last day of last month');
                return [$lastMonthStart->format('Y-m-d'), $lastMonthEnd->format('Y-m-d')];

            case 'this_year':
                return [$now->format('Y') . '-01-01', $now->format('Y-m-d')];

            case 'last_year':
                $lastYear = $now->format('Y') - 1;
                return [$lastYear . '-01-01', $lastYear . '-12-31'];

            default:
                $thirtyDaysAgo = clone $now;
                $thirtyDaysAgo->sub(new DateInterval('P30D'));
                return [$thirtyDaysAgo->format('Y-m-d'), $now->format('Y-m-d')];
        }
    }

    /**
     * 获取发布统计数据
     *
     * @param string|null $startDate
     * @param string|null $endDate
     * @param int|null $sourceSiteId 源站筛选
     * @return array
     */
    private function getReleaseStatistics(?string $startDate, ?string $endDate, ?int $sourceSiteId = null): array
    {
        // 获取所有站点（用于初始化统计数据）
        $sites = SiteModel::pluck('site_name', 'id')->toArray();

        // 构建查询
        $query = $this->model->newQuery();

        // 添加源站筛选（通过关联查询）
        if ($sourceSiteId) {
            $query->whereHas('torrentTask', function($q) use ($sourceSiteId) {
                $q->where('site_id', $sourceSiteId);
            });
        }

        // 添加时间筛选 - 尝试多种可能的时间字段
        if ($startDate) {
            // 优先使用 updated_at，如果不存在则使用 created_at
            $query->where(function($q) use ($startDate) {
                $q->where('updated_at', '>=', $startDate . ' 00:00:00')
                  ->orWhere('created_at', '>=', $startDate . ' 00:00:00');
            });
        }
        if ($endDate) {
            $query->where(function($q) use ($endDate) {
                $q->where('updated_at', '<=', $endDate . ' 23:59:59')
                  ->orWhere('created_at', '<=', $endDate . ' 23:59:59');
            });
        }

        // 按站点和任务状态分组统计
        $results = $query->selectRaw('site_id, task_status, COUNT(*) as count')
            ->groupBy('site_id', 'task_status')
            ->get()
            ->groupBy('site_id');

        $statistics = [];

        // 初始化所有站点的统计数据
        foreach ($sites as $siteId => $siteName) {
            $statistics[] = [
                'site_id' => $siteId,
                'site_name' => $siteName,
                'task_status_0' => 0, // 待发布
                'task_status_1' => 0, // 发布成功
                'task_status_2' => 0, // 资源重复
                'task_status_3' => 0, // 发布失败
                'task_status_4' => 0, // 任务不存在
                'task_status_5' => 0, // 任务已结束
                'task_status_6' => 0, // 源站种子不存在
                'task_status_99' => 0, // 完结
                'total' => 0
            ];
        }

        // 填充实际统计数据
        foreach ($results as $siteId => $siteResults) {
            foreach ($statistics as &$stat) {
                if ($stat['site_id'] == $siteId) {
                    $total = 0;
                    foreach ($siteResults as $result) {
                        $statusKey = 'task_status_' . $result->task_status;
                        $stat[$statusKey] = $result->count;
                        $total += $result->count;
                    }
                    $stat['total'] = $total;
                    break;
                }
            }
        }

        // 过滤掉总计为0的站点，并按站点名称排序
        $filteredStatistics = array_filter($statistics, function($stat) {
            return $stat['total'] > 0;
        });

        $filteredStatistics = array_values($filteredStatistics);

        usort($filteredStatistics, function($a, $b) {
            return strcmp($a['site_name'], $b['site_name']);
        });

        return $filteredStatistics;
    }

}
